;(function (doc, initTools) {
  var Tab = function () {
  	this.oTab = doc.getElementsByClassName('J_tab')[0]

  	this.oNav = doc.createElement('div')
  	this.oPage = doc.createElement('div')
  	this.oNav.className = 'nav'
  	this.oPage.className = 'page'

  	this.navTpl = doc.getElementById('J_navTpl').innerHTML
  	this.pageTpl = doc.getElementById('J_pageTpl').innerHTML
  	this.data = JSON.parse(doc.getElementById('J_defaultData').innerHTML)

  	this.curIdx = 0
    this.htmlCache = {}

  	this.init()
  }

  Tab.prototype.init = function () {
  	this.render()
  	this.bindEvent()
  }

  Tab.prototype.render = function () {
    var oFrag = document.createDocumentFragment()

    this.oNav.innerHTML = this.renderNav(this.data)
    this.oPage.innerHTML = this.renderPage(this.data, this.curIdx)

    oFrag.appendChild(this.oNav)
    oFrag.appendChild(this.oPage)
    this.oTab.appendChild(oFrag)
  }

  Tab.prototype.renderNav = function (data) {
  	var list = ''

    data.forEach(function (item, index) {
      list += initTools.tplReplace(this.navTpl, {
        navClass: !index ? 'item current' : 'item',
        city_name: item.city_name,
        id: item.id
      })
    }, this)

    return list
  }

  Tab.prototype.renderPage = function (data, index) {
    if (!this.htmlCache[index]) {
      var dataItem = data[index]

      this.htmlCache[index] = initTools.tplReplace(this.pageTpl, {
        city_name: dataItem.city_name,
        intro: dataItem.intro,
        img: dataItem.img
      })
    }
    return this.htmlCache[index]
  }

  Tab.prototype.bindEvent = function () {
    this.oNav = this.oTab.getElementsByClassName('nav')[0]
    this.oPage = this.oTab.getElementsByClassName('page')[0]
    this.oNavItems = this.oNav.getElementsByClassName('item')

  	this.oNav.addEventListener('click', this.onNavClick.bind(this), false)
  }

  Tab.prototype.onNavClick = function (ev) {
  	const tar = initTools.getTarget(ev), className = tar.className
  	className === 'item' && this.changePage(tar, this.data)
  }

  Tab.prototype.changePage = function (target, data) {
    this.setCurrent('remove')
    this.curIdx = [].indexOf.call(this.oNavItems, target)
    this.setCurrent('add')

    this.oPage.innerHTML = this.renderPage(data, this.curIdx)
  }

  Tab.prototype.setCurrent = function (field) {
  	switch (field) {
      case 'add':
        this.oNavItems[this.curIdx].className += ' current'
        break
      case 'remove':
        this.oNavItems[this.curIdx].className = 'item'
        break
      default:
        break
  	}
  }
  window.Tab = Tab
})(document, initTools)

new Tab()







